﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Line64.ImageFlow.Activities
{

    public sealed class ChangeSizeActivity : CodeActivity
    {
        
        public InOutArgument<Bitmap> Bitmap { get; set; }

        public InArgument<int?> NewWidth { get; set; }

        public InArgument<int?> NewHeight { get; set; }

        protected override void Execute(CodeActivityContext context)
        {

            Image bitmap = this.Bitmap.Get(context);
            int? newWidth = this.NewWidth.Get(context);
            int? newHeight = this.NewHeight.Get(context);

            using (bitmap)
            {

                newWidth = newWidth ?? this.GetProportionalValue(bitmap.Width, bitmap.Height, newHeight.Value);
                newHeight = newHeight ?? this.GetProportionalValue(bitmap.Height, bitmap.Width, newWidth.Value);

                Image output = new Bitmap(newWidth.Value, newHeight.Value);

                Graphics graphic = Graphics.FromImage(output);

                using (graphic)
                {

                    graphic.CompositingQuality = CompositingQuality.HighQuality;
                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    Rectangle rectangle = new Rectangle(0, 0, newWidth.Value, newHeight.Value);
                    
                    graphic.DrawImage(bitmap, rectangle);

                    this.Bitmap.Set(context, output);

                }

            }            

        }

        private int GetProportionalValue(int originalValue, int otherDimOriginalValue, int otherDimNewValue)
        {

            return Convert.ToInt32(((double)originalValue * (double)otherDimNewValue) / (double)otherDimOriginalValue);

        }

    }

}
